<template>
  <div>
    <el-form ref="form" :rules="rules" size="mini" inline :model="form" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="视图类型" prop="reportType">
            <el-select ref="reportType" v-model="form.reportType">
              <el-option v-for="item in reportTypeList" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表" prop="table">
            <el-select  @change="changeTable" v-model="form.table">
              <el-option v-for="item in tableList" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择列" prop="selectField">
            <el-select ref="selectField" v-model="form.selectField" clearable style="width: 200px;">
              <el-option v-for="item in tableInfo.selectColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row>
          <el-col>
            <el-form-item label="统计方式">
              <el-radio-group v-model="form.statType" size="mini">
                <el-radio-button label="求和"></el-radio-button>
                <el-radio-button label="平均"></el-radio-button>
                <el-radio-button label="最大"></el-radio-button>
                <el-radio-button label="最小"></el-radio-button>
              </el-radio-group>
              <el-select ref="statField" v-model="form.statField" clearable>
                <el-option v-for="item in tableInfo.aggregationColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="计数">
              <el-select ref="countField" v-model="form.countField" clearable>
                <el-option v-for="item in tableInfo.countColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="起始日期" prop="from">
              <el-date-picker type="date" placeholder="起始日期" v-model="form.from" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" prop="to">
              <el-date-picker type="date" placeholder="结束日期" v-model="form.to" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <div id="main" style="height: 440px;"></div>
  </div>
</template>

<script>
  import {list, tableList} from '@/api/crm/report'
  import * as echarts from "echarts";
  export default {
    name: "reportChart",
    data() {
      return {
        //解析后的数据，数据项为map
        dataList: [],
        //解析后的数据，数据项为Object，给表格用的
        dataObjectList: [],
        tableColumns: [],
        columnMap: new Map(),
        form: {
          from: '2020-01-01 00:00:00',
          to: '2022-10-01 23:59:59',
          reportType: 'MONTH',
          table: 'tb_contract',
          selectField: '',
          statField: '',
          countField: '',
          dateField: 'create_time',
          statType: '求和',
          maxFields: [],
          minFields: [],
          avgFields: [],
          sumFields: [],
          countFields: [],
        },
        rules: {
          reportType:[{ required: true, message: "报表类型不能为空", trigger: "blur" }],
          table:[{ required: true, message: "数据表不能为空", trigger: "blur" }],
          selectField:[{ required: true, message: "列不能为空", trigger: "blur" }],
          from:[{ required: true, message: "起始日期不能为空", trigger: "blur" }],
          to:[{ required: true, message: "结束日期不能为空", trigger: "blur" }],
        },
        tableInfo: [],
        reportTypeList:[
          {'label':'日', 'value':'DATE'},
          {'label':'周', 'value':'WEEK'},
          {'label':'月', 'value':'MONTH'},
          {'label':'季', 'value':'QUARTER'},
          {'label':'年', 'value':'YEAR'},
        ],
        tableList:[
          {'label':'合同表', 'value':'tb_contract'},
          {'label':'商机表', 'value':'tb_business'},
        ],

      }
    },
    created() {
      // this.refreshData()
      this.tableInfo = tableList['tb_contract']
    },
    methods: {
      onSubmit() {
        this.$refs.form.validate(valid=>{
          if(valid) {
            if(this.isEmpty(this.form.statField)  && this.isEmpty(this.form.countField)) {
              this.$alert('至少选择一个统计操作')
              return false
            }
            if(this.form.statField != '') {
              if(this.form.statType == '求和') {
                this.form.sumFields = [this.form.statField];
              } else if(this.form.statType == '最大') {
                this.form.maxFields = [this.form.statField];
              } else if(this.form.statType == '最小') {
                this.form.minFields = [this.form.statField];
              } else if(this.form.statType == '平均') {
                this.form.avgFields = [this.form.statField];
              }
            }
            this.form.columns = [this.form.selectField];
            if(this.form.countField && this.form.countField != '') {
              this.form.countFields = [this.form.countField];
            }
            this.refreshData();
          }
        })
      },
      refreshData() {
        list(this.form).then(resp => {
            this.renderEcharts(resp.data)
        })
      },
      changeTable(val) {
        this.form.selectField = '',
        this.form.statField = '';
        this.form.countField = '';
        this.form.sumFields.length = 0;
        this.form.avgFields.length = 0;
        this.form.maxFields.length = 0;
        this.form.minFields.length = 0;
        this.form.countFields.length = 0;
        this.tableInfo = tableList[val]
      },
      isEmpty(obj) {
        return !obj || obj.length == 0;
      },
      renderEcharts(obj) {
        let dateArr = [];
        let statArr = [];
        let countArr = [];
        let prefixMap = new Map();
        prefixMap.set('求和', 'sum_')
        prefixMap.set('最大', 'max_')
        prefixMap.set('最小', 'min_')
        prefixMap.set('平均', 'avg_')
        prefixMap.set('计数', 'count_')
        obj.forEach(item => {
          dateArr.push(this.formatDateTitle(item));
          statArr.push(parseFloat(item[prefixMap.get(this.form.statType) + this.form.statField]).toFixed(2));
          if(this.form.countField && this.form.countField != '') {
            countArr.push(item['count_' + this.form.countField]);
          }
        });
        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom);
        var option;

        option = {
          title: {
            text: this.$refs.selectField.selected.label + '统计' + this.$refs.reportType.selected.label + '报表',
            subtext: ''
          },
          tooltip: {
            trigger: 'axis',
            show: false
          },
          legend: {
            data: []
          },
          toolbox: {
            show: true,
            feature: {
              dataView: { show: true, readOnly: false },
              magicType: { show: true, type: ['line', 'bar'] },
              restore: { show: true },
              saveAsImage: { show: true }
            }
          },
          calculable: true,
          //X轴上柱子的数据
          xAxis: [
            {
              type: 'category',
              // prettier-ignore
              data: []
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
          ],
          dataZoom : [
            //1.横向使用滚动条
            {
              type: 'slider',//有单独的滑动条，用户在滑动条上进行缩放或漫游。inside是直接可以是在内部拖动显示
              show: true,//是否显示 组件。如果设置为 false，不会显示，但是数据过滤的功能还存在。
              start: 0,//数据窗口范围的起始百分比0-100
              end: 80,//数据窗口范围的结束百分比0-100
              xAxisIndex: [0],// 此处表示控制第一个xAxis，设置 dataZoom-slider 组件控制的 x轴 可是已数组[0,2]表示控制第一，三个；xAxisIndex: 2 ，表示控制第二个。yAxisIndex属性同理
              bottom:-10 //距离底部的距离
            },

          ],
        };
        //注意，必须用这种语法来传递数据
        option.xAxis[0].data = dateArr;
        if(this.form.statField && this.form.statField != '') {
          this.addBar(option, this.$refs.statField.selected.label + this.form.statType)
          option.series[option.series.length-1].data = statArr;
        }
        if(this.form.countField && this.form.countField != '') {
          this.addBar(option, this.$refs.countField.selected.label + '计数值')
          option.series[option.series.length-1].data = countArr;
        }
        // setOption有3个属性，setOption(option,notMerge,lazyUpdate); 第二个notMerge默认为false,即默认合并两个数据
        option && myChart.setOption(option, true);
      },
      formatDateTitle(item) {
        let reportType = this.$refs.reportType.selected.label;
        let selectField = item[this.form.selectField] ? item[this.form.selectField] : '';
        if(reportType == '月' || reportType == '周' || reportType == '季') {
          return item.year + '年' + item.date + reportType + selectField
        } else if(reportType == '年') {
          return item.year + '年' + selectField
        } else {
          return item.date + selectField
        }
      },
      addBar(option, legendData) {
        let series = {
            name: legendData,
            type: 'bar',
            barWidth : 20, //柱图宽度
            data: [

            ],
            //在柱子顶端展示数据的最大值最小值气泡
            // markPoint: {
            //     data: [
            //         { type: 'max', name: 'Max' },
            //         { type: 'min', name: 'Min' }
            //     ]
            // },
            //展示数据平均值线
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            // 用于在每根柱子上展示数据
            label: {
              show: true,
              position: 'top',
              color:'black'
            }
        };
        option.legend.data.push(legendData);
        option.series.push(series);
      },
    }
  }
</script>

<style scoped>
  .el-select,.el-input {
    width: 140px;
  }
</style>
